<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.bookmanager.model.Book" %>
<%@ page import="java.util.List" %>
<%@ page import="com.bookmanager.model.User" %>
<%@ page import="java.util.Map" %>
<%
    // 检查用户登录
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login.jsp");
        return;
    }

    List<Book> books = (List<Book>) request.getAttribute("books");
    String keyword = (String) request.getAttribute("keyword");
    if (keyword == null) keyword = "";
%>
<html>
<head>
    <title>图书查询</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
        }
        .search-box {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .search-box input {
            padding: 10px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .search-box button {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-box button:hover {
            background: #0056b3;
        }
        .book-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        .book-table th, .book-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        .book-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .book-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        .book-table tr:hover {
            background-color: #e9ecef;
        }
        .status-available {
            color: #28a745;
            font-weight: bold;
        }
        .status-borrowed {
            color: #dc3545;
            font-weight: bold;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .action-buttons button {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        .btn-borrow {
            background: #28a745;
            color: white;
        }
        .btn-detail {
            background: #17a2b8;
            color: white;
        }
        .btn-return {
            background: #ffc107;
            color: white;
        }
        .btn-favorite {
            background: #e83e8c;
            color: white;
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.85rem;
            transition: all 0.3s ease;
        }

        .btn-favorite:hover {
            background: #d91a72;
            transform: scale(1.05);
        }

        .btn-favorite.favorited {
            background: #28a745;
        }

        .btn-favorite.favorited:hover {
            background: #218838;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>📚 图书查询管理系统</h1>
        <div>
            <span>欢迎，<%= user.getUsername() %></span>
            <% if ("admin".equals(user.getRole())) { %>
            <a href="admin/dashboard.jsp" style="margin-left: 15px; color: #007bff;">管理后台</a>
            <% } else { %>
            <a href="user/dashboard.jsp" style="margin-left: 15px; color: #007bff;">用户中心</a>
            <% } %>
            <a href="<%= request.getContextPath() %>/logout" style="margin-left: 15px; color: #dc3545;">退出登录</a>
        </div>
    </div>

    <%
        String message = request.getParameter("message");
        if (message != null) {
            String alertClass = "";
            String alertText = "";

            if ("borrow_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "借阅成功！";
            } else if ("borrow_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "借阅失败，请重试！";
            } else if ("return_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "归还成功！";
            } else if ("return_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "归还失败，请重试！";
            }else if (message.contains("收藏成功")) {
                alertClass = "alert-success";
                alertText = message;
            } else if (message.contains("收藏失败") || message.contains("取消收藏")) {
                alertClass = "alert-danger";
                alertText = message;
            }

            if (!alertText.isEmpty()) {
    %>
    <div class="alert <%= alertClass %>" style="padding: 10px; margin-bottom: 20px; border-radius: 4px; background: <%= alertClass.contains("success") ? "#d4edda" : "#f8d7da" %>; color: <%= alertClass.contains("success") ? "#155724" : "#721c24" %>; border: 1px solid <%= alertClass.contains("success") ? "#c3e6cb" : "#f5c6cb" %>;">
        <%= alertText %>
    </div>
    <%
            }
        }
    %>

    <div class="search-box">
        <form action="books" method="get" style="display: flex; gap: 10px;">
            <input type="hidden" name="action" value="search">
            <input type="text" name="keyword" value="<%= keyword %>" placeholder="输入书名、作者或ISBN进行搜索">
            <button type="submit">搜索</button>
            <a href="books" style="padding: 10px 15px; background: #6c757d; color: white; text-decoration: none; border-radius: 4px;">显示全部</a>
        </form>
    </div>

    <% if (books != null && !books.isEmpty()) { %>
    <table class="book-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>ISBN</th>
            <th>书名</th>
            <th>作者</th>
            <th>出版社</th>
            <th>价格</th>
            <th>分类</th>
            <th>可借数量</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <% for (Book book : books) { %>
        <tr>
            <td><%= book.getBookId() %></td>
            <td><%= book.getIsbn() %></td>
            <td><strong><%= book.getTitle() %></strong></td>
            <td><%= book.getAuthor() %></td>
            <td><%= book.getPublisher() %></td>
            <td>¥<%= book.getPrice() != null ? book.getPrice() : "0.00" %></td>
            <td><%= book.getCategory() != null ? book.getCategory() : "未分类" %></td>
            <td><%= book.getAvailableCopies() %>/<%= book.getTotalCopies() %></td>
            <td class="status-<%= book.getStatus() %>">
                <%= "available".equals(book.getStatus()) ? "可借" : "已借出" %>
            </td>
            <td class="action-buttons">
                <% if ("admin".equals(user.getRole())) { %>
                <button class="btn-edit" onclick="editBook(<%= book.getBookId() %>)">编辑</button>
                <% } %>

                <% if ("available".equals(book.getStatus()) && book.getAvailableCopies() > 0) { %>
                <button class="btn-borrow" onclick="borrowBook(<%= book.getBookId() %>)">借阅</button>
                <% } else { %>
                <button class="btn-return" onclick="returnBook(<%= book.getBookId() %>)">归还</button>
                <% } %>
                <button class="btn-detail" onclick="showDetail(<%= book.getBookId() %>)">详情</button>
                <%
                    // 获取收藏状态
                    Map<Integer, Boolean> favoriteStatusMap = (Map<Integer, Boolean>) request.getAttribute("favoriteStatusMap");
                    boolean isFavorite = false;
                    if (favoriteStatusMap != null) {
                        Boolean favoriteStatus = favoriteStatusMap.get(book.getBookId());
                        isFavorite = favoriteStatus != null ? favoriteStatus : false;
                    }
                %>

                <button class="btn-favorite <%= isFavorite ? "favorited" : "" %>"
                        onclick="toggleFavorite(<%= book.getBookId() %>, <%= isFavorite %>)"
                        data-book-id="<%= book.getBookId() %>"
                        data-is-favorite="<%= isFavorite %>">
                    <%= isFavorite ? "★ 已收藏" : "☆ 收藏" %>
                </button>
            </td>
        </tr>
        <% } %>
        </tbody>
    </table>
    <% } else { %>
    <div style="text-align: center; padding: 40px; color: #6c757d;">
        <p style="font-size: 18px;">📖 没有找到相关图书</p>
        <p>请尝试其他搜索关键词</p>
    </div>
    <% } %>
</div>

<script>
    function borrowBook(bookId) {
        if (confirm('确定要借阅这本书吗？')) {
            window.location.href = 'borrow?action=borrow&bookId=' + bookId;
        }
    }

    function returnBook(bookId) {
        if (confirm('确定要归还这本书吗？')) {
            window.location.href = 'borrow?action=return&bookId=' + bookId;
        }
    }

    function showDetail(bookId) {
        window.location.href = 'book-detail?bookId=' + bookId;
    }

    function editBook(bookId) {
        window.location.href = 'books?action=edit&bookId=' + bookId;
    }

    function toggleFavorite(bookId, isCurrentlyFavorite) {
        const action = isCurrentlyFavorite ? 'remove' : 'add';
        const confirmMessage = isCurrentlyFavorite ?
            '确定要取消收藏这本书吗？' : '确定要收藏这本书吗？';

        if (confirm(confirmMessage)) {
            // 创建表单提交收藏请求
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'favorite';

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = action;
            form.appendChild(actionInput);

            const bookIdInput = document.createElement('input');
            bookIdInput.type = 'hidden';
            bookIdInput.name = 'bookId';
            bookIdInput.value = bookId;
            form.appendChild(bookIdInput);

            document.body.appendChild(form);
            form.submit();
        }
    }
</script>
</body>
</html>